package com.tony.lock;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author tonywang
 * @date 8/6/2018
 */
public class ConditionUseCase {
    Lock lock = new ReentrantLock();
    Condition condition = lock.newCondition();
    static int count = 0;
    public void conditionWait() throws InterruptedException {
        lock.lock();
        try {
            while (count < 5) {
                count++;
                System.out.println("自增 count:" + count);
                condition.signal();
            }
            System.out.println("停止生产,开始消费");
            Thread.sleep(1000);
            condition.await();
        } finally {
            lock.unlock();
        }
    }

    public void conditionSignal() throws InterruptedException {
        lock.lock();
        try {
            while (count  > 0) {
                count--;
                System.out.println("自减 count:" + count);
                condition.signal();
            }
            System.out.println("停止消费，开始生产");
            condition.await();
            Thread.sleep(1000);
        } finally {
            lock.unlock();
        }
    }

    static class Producer implements Runnable {
        ConditionUseCase conditionUseCase;
        Producer(ConditionUseCase conditionUseCase) {
            this.conditionUseCase = conditionUseCase;
        }
        @Override
        public void run() {
            try {
                while (true) {
                    conditionUseCase.conditionWait();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
   static class Consumers implements Runnable {
        ConditionUseCase conditionUseCase;
        Consumers(ConditionUseCase conditionUseCase) {
            this.conditionUseCase = conditionUseCase;
        }
        @Override
        public void run() {
            try {
                while (true) {
                    conditionUseCase.conditionSignal();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        ConditionUseCase conditionUseCase = new ConditionUseCase();
        Thread producer = new Thread(new Producer(conditionUseCase));
        Thread consumers = new Thread(new Consumers(conditionUseCase));
        producer.start();
        consumers.start();
        producer.join();
        consumers.join();
        System.out.println("exit");
    }



}
